package pers.myutil.local.conversion.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间转换
 */
public class DateConversion {

    /**
     * 由出生日期获得年龄
     * @param birthDay 生日
     * @return 年龄
     */
    public static int getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException("出生日期能大于当前日期！");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }

    /**
     * 时间转换String转换为Date
     * @param dateString String时间
     * @param pattern 时间格式
     * @return Date对象
     */
    public static Date springToDate(String dateString,String pattern) throws ParseException {
        return new SimpleDateFormat(pattern).parse(dateString);
    }

    public static String dateToString(Date date,String pattern){
        return new SimpleDateFormat(pattern).format(date);
    }

    public static void main(String[] args) {
        System.out.println(dateToString(new Date(),"yyyy年MM月dd日 HH时mm分ss秒"));
    }
}
